const db = uniCloud.database()
const collection = db.collection('iss-wallpaper-image')
const favoriteCollection = db.collection('iss-wallpaper-favorite')
const downloadCollection = db.collection('iss-wallpaper-download')
const ratingCollection = db.collection('iss-wallpaper-rating')
const ApiResponse = require('iss-api-response')
const ErrorMessage = ApiResponse.ErrorMessage
const commonMixin = require('common-mixin')

module.exports = {
  ...commonMixin,
  
  /**
   * 获取壁纸图片列表
   * @param {number} pageNum 当前页码（random为false时有效）
   * @param {number} pageSize 每页数量
   * @param {boolean} random 是否随机模式
   * @param {string} classid 分类ID筛选条件
   * @param {string} keyword 关键词搜索（模糊匹配description和tabs）
   * @returns {object} 返回图片列表和分页信息
   */
  async getImageList({pageNum = 1, pageSize = 10, random = false, classid = '', keyword = ''}) {
    try {
      // 基础查询条件 - 只查询已审核通过的图片
      let whereCondition = { status: true }
      
      // 添加分类筛选条件
      if (classid) {
        whereCondition.classid = classid
      }
      
      // 添加关键词搜索条件
      if (keyword) {
        whereCondition.$or = [
          { description: new RegExp(keyword, 'i') },
          { tabs: new RegExp(keyword, 'i') }
        ]
      }
      
      let query = collection.where(whereCondition)
      let res, total
      
      if (random) {
        // 随机模式 - 使用aggregate的sample操作实现随机获取
        const aggregateRes = await collection
          .aggregate()
          .match(whereCondition)
          .sample({ size: pageSize })
          .end()
        res = { data: aggregateRes.data }
        const countRes = await collection.where(whereCondition).count()
        total = countRes.total
      } else {
        // 分页模式
        const offset = (pageNum - 1) * pageSize
        res = await query
          .orderBy('createTime', 'desc') // 默认按创建时间倒序
          .skip(offset)
          .limit(pageSize)
          .get()
        const countRes = await collection.where(whereCondition).count()
        total = countRes.total
      }
      
      // 返回数据
      return ApiResponse.success({
        list: res.data,
        total,
        pageNum: random ? 1 : pageNum,
        pageSize: random ? res.data.length : pageSize,
        isLogin: !!this.userInfo // 额外返回是否登录状态
      })
      
    } catch (e) {
      console.error(ErrorMessage.GET_IMAGELIST_ERROR, e)
      return ApiResponse.serverError(ErrorMessage.GET_IMAGELIST_ERROR)
    }
  },
  
  /**
     * 根据ID获取壁纸图片信息
     * @param {string} id 壁纸图片的ID
     * @returns {object} 返回壁纸图片信息
     */
    async getImageById({id}) {
      try {
		// 校验 id 是否为有效的字符串
		if (typeof id!== 'string' || id.trim() === '') {
		  return ApiResponse.badRequest(ErrorMessage.INVALID_ID)
		}
        const res = await collection.doc(id).get()
        if (res.data.length === 0) {
          return ApiResponse.notFound(ErrorMessage.IMAGE_NOT_FOUND)
        }
        return ApiResponse.success(res.data[0])
      } catch (e) {
        console.error(ErrorMessage.GET_IMAGE_BY_ID_ERROR, e)
        return ApiResponse.serverError(ErrorMessage.GET_IMAGE_BY_ID_ERROR)
      }
    },
	
	/**
	 * 获取壁纸详情及用户相关行为信息
	 * @param {string} id 壁纸ID
	 * @returns {object} 包含壁纸详情、收藏状态、用户评分和下载次数
	 */
	async getImageDetailById({id}) {
	  try {
	    // 校验ID
	    if (typeof id !== 'string' || id.trim() === '') {
	      return ApiResponse.badRequest(ErrorMessage.INVALID_ID)
	    }
	
	    // 获取壁纸基本信息
	    const wallpaperRes = await collection.doc(id).get()
	    if (wallpaperRes.data.length === 0) {
	      return ApiResponse.notFound(ErrorMessage.IMAGE_NOT_FOUND)
	    }
	
	    const result = {
	      ...wallpaperRes.data[0],
	      isFavorite: false,
	      userScore: null,
	      downloadCount: 0
	    }
	
	    // 如果用户已登录，获取用户相关行为信息
	    if (this.userInfo && this.userInfo.uid) {
			
	      // 并行查询收藏状态、用户评分和下载次数
	      const [favoriteRes, ratingRes, downloadRes] = await Promise.all([
	        favoriteCollection.where({
	          user_id: this.userInfo.uid,
	          wallpaper_id: id
	        }).get(),
	        
	        ratingCollection.where({
	          user_id: this.userInfo.uid,
	          wallpaper_id: id
	        }).get(),
	        
	        downloadCollection.where({
	          user_id: this.userInfo.uid,
	          wallpaper_id: id
	        }).count()
	      ])
		  
		  // console.log('wallpaperid&&uid=',this.userInfo.uid,id, favoriteRes)
	
	      // 设置收藏状态
	      if (favoriteRes.data.length > 0) {
	        result.isFavorite = true
	        result.favoriteId = favoriteRes.data[0]._id
	        result.favoriteTime = favoriteRes.data[0].create_time
	      }
	
	      // 设置用户评分
	      if (ratingRes.data.length > 0) {
	        result.userScore = ratingRes.data[0].score
	        result.ratingTime = ratingRes.data[0].update_time
	      }
	
	      // 设置下载次数
	      result.downloadCount = downloadRes.total
	    }
	
	    return ApiResponse.success(result)
	
	  } catch (e) {
	    console.error(ErrorMessage.GET_IMAGE_DETAIL_ERROR, e)
	    return ApiResponse.serverError(ErrorMessage.GET_IMAGE_DETAIL_ERROR)
	  }
	},
	
	/**
	   * 用户下载壁纸，添加或更新下载记录
	   * @param {string} id 壁纸ID
	   * @returns {object} 操作结果
	   */
	  async downloadWallpaperLog({ id }) {
	    try {
	      if (!this.userInfo) {
	        return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
	      }
	
	      // 检查壁纸是否存在
	      const wallpaperRes = await collection.doc(id).get()
	      if (wallpaperRes.data.length === 0) {
	        return ApiResponse.notFound(ErrorMessage.IMAGE_NOT_FOUND)
	      }
	
	      const userId = this.userInfo.uid;
	      const existingDownload = await downloadCollection
	        .where({
	          user_id: userId,
	          wallpaper_id: id
	        })
	        .get()
	
	      if (existingDownload.data.length > 0) {
	        // 用户已下载过该壁纸，更新下载时间和 IP
	        await downloadCollection.doc(existingDownload.data[0]._id).update({
	          update_time: Date.now(),
	          ip: this.clientInfo.clientIP || ''
	        })
	      } else {
	        // 用户未下载过该壁纸，添加新的下载记录
	        await downloadCollection.add({
	          user_id: userId,
	          wallpaper_id: id,
	          create_time: Date.now(),
	          update_time: Date.now(),
	          ip: this.clientInfo.clientIP || ''
	        })
	      }
		  
		  console.log('this.userInfo=',this.userInfo)
	
	      return ApiResponse.success({
	        message: '下载记录更新成功'
	      })
	    } catch (e) {
	      console.error(ErrorMessage.DOWNLOAD_WALLPAPER_ERROR, e)
	      return ApiResponse.serverError(ErrorMessage.DOWNLOAD_WALLPAPER_ERROR)
	    }
	  },
	  
	  /**
	   * 切换壁纸收藏状态（收藏/取消收藏）
	   * @param {string} id 壁纸ID
	   * @returns {object} 操作结果，包含当前收藏状态
	   */
	  async toggleFavorite({id}) {
	    try {
	      if (!this.userInfo) {
	        return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
	      }
	      
	      // 检查壁纸是否存在
	      const wallpaperRes = await collection.doc(id).get()
	      if (wallpaperRes.data.length === 0) {
	        return ApiResponse.notFound(ErrorMessage.IMAGE_NOT_FOUND)
	      }
	      
	      // 检查当前收藏状态
	      const favoriteRes = await favoriteCollection
	        .where({
	          user_id: this.userInfo.uid,
	          wallpaper_id: id
	        })
	        .get()
	      
	      if (favoriteRes.data.length > 0) {
	        // 已收藏，执行取消收藏操作
	        await favoriteCollection.doc(favoriteRes.data[0]._id).remove()
	        return ApiResponse.success({
	          isFavorite: false,
	          message: '已取消收藏'
	        })
	      } else {
	        // 未收藏，执行收藏操作
	        await favoriteCollection.add({
	          user_id: this.userInfo.uid,
	          wallpaper_id: id,
	          create_time: Date.now(),
			  update_time: Date.now()
	        })
	        return ApiResponse.success({
	          isFavorite: true,
	          message: '收藏成功'
	        })
	      }
	      
	    } catch (e) {
	      console.error(ErrorMessage.TOGGLE_FAVORITE_ERROR, e)
	      return ApiResponse.serverError(ErrorMessage.TOGGLE_FAVORITE_ERROR)
	    }
	  },
		
		/**
		 * 新增壁纸评分方法
		 * @param {string} id 壁纸ID
		 * @param {number} score 评分值
		 * @returns {object} 操作结果
		 */
		async rateWallpaper({id, score}) {
		  try {
		    if (!this.userInfo) {
		      return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
		    }
		    
		    // 检查评分范围
		    if (typeof score !== 'number' || score < 0 || score > 5) {
		      return ApiResponse.badRequest(ErrorMessage.INVALID_SCORE)
		    }
		    
		    // 检查壁纸是否存在
		    const wallpaperRes = await collection.doc(id).get()
		    if (wallpaperRes.data.length === 0) {
		      return ApiResponse.notFound(ErrorMessage.IMAGE_NOT_FOUND)
		    }
		    
		    const userId = this.userInfo.uid;
		    const ratingDoc = ratingCollection.doc({
		      user_id: userId,
		      wallpaper_id: id
		    });
		    
		    // 检查用户是否已评分
		    const existingRating = await ratingDoc.get();
		    const isNewRating = existingRating.data.length === 0;
		    
			if(isNewRating) {
				await ratingCollection.add({
				  user_id: userId,
				  wallpaper_id: id,
				  score,
				  create_time: Date.now(),
				  update_time: Date.now()
				})
			} else {
				// 更新或创建评分记录
				await ratingDoc.set({
				  score: score,
				  create_time: isNewRating ? Date.now() : existingRating.data[0].create_time,
				  update_time: Date.now()
				}, {
				  upsert: true
				})
			}
		    
		    // 计算该壁纸的平均评分
		    const aggregateRes = await ratingCollection.aggregate()
		      .match({
		        wallpaper_id: id
		      })
		      .group({
		        _id: id,  // 直接使用壁纸ID作为分组ID
		        averageScore: { $avg: '$score' },
		        ratingCount: { $sum: 1 }
		      })
		      .end()
		    
			let avgScore = 5
			let rCount = 1
		    if (aggregateRes.data.length > 0) {
		      const { averageScore, ratingCount } = aggregateRes.data[0]
		      avgScore = parseFloat(averageScore.toFixed(1))
			  rCount = ratingCount
		      // 更新壁纸表中的评分
		      await collection.doc(id).update({
		        score: avgScore, // 保留一位小数
		        ratingCount: ratingCount
		      })
		    }
		    
		    return ApiResponse.success({
		      message: isNewRating ? '评分成功' : '评分更新成功',
			  score:avgScore,
			  ratingCount:rCount
		    })
		    
		  } catch (e) {
		    console.error(ErrorMessage.RATE_WALLPAPER_ERROR, e)
		    return ApiResponse.serverError(ErrorMessage.RATE_WALLPAPER_ERROR)
		  }
		}
}